package com.yunxi.yunxicaiproject.service.impl;

import com.yunxi.yunxicaiproject.entity.dto.LoginDTO;
import com.yunxi.yunxicaiproject.entity.po.AiStudent;
import com.yunxi.yunxicaiproject.mapper.AiStudentMapper;
import com.yunxi.yunxicaiproject.service.ILoginService;
import com.yunxi.yunxicaiproject.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yunxi.yunxicaiproject.entity.vo.LoginVO;

import java.security.NoSuchAlgorithmException;
import java.util.Map;

import static org.codehaus.groovy.runtime.EncodingGroovyMethods.md5;

@Service
public class ILoginServiceImpl implements ILoginService {
    @Autowired
    AiStudentMapper aiStudentMapper;

    @Override
    public R login(LoginDTO loginDTO) {
        if (loginDTO.getName() == null || loginDTO.getName().isEmpty() ||
                loginDTO.getPassword() == null || loginDTO.getPassword().isEmpty()) {
            return R.error("用户名和密码不能为空");
        }

        AiStudent byId = aiStudentMapper.selectById(loginDTO.getName());
        LoginVO vo = new LoginVO();
        BeanUtils.copyProperties(byId, vo);
        //将接收的密码md5加密
        String md5Password;
        try {
            md5Password = md5(loginDTO.getPassword());
        } catch (NoSuchAlgorithmException e) {
            return R.error("服务器加密错误");
        }

        if (byId != null && byId.getPassword().equals(md5Password)) {
            return R.ok().put("data", vo);
        } else
            return R.error("用户名或密码错误");
    }
}
